package com.atguigu.tingshu.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/***
 * 全局过滤器
 */
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    /**
     * token校验
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取路径
        if (request.getPath().value().contains("/api/user/wxLogin/wxLogin")){
            //登录直接放行
            return chain.filter(exchange);
        }
        //获取请求头
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            //从cookie中获取token
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            if (cookies != null) {
                //获取cookie对象
                HttpCookie httpCookie = cookies.getFirst("token");
                if (httpCookie != null) {
                    token = httpCookie.getValue();
                    //将token放回请求头中
                    request.mutate().header("token", token);
                }
            }
        }
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //请求终止
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    /**
     * 运行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
